import importlib
import sys
import os
import traceback
import time
from cv2 import cv2
sys.path.append(os.getcwd().replace('\\', '/')+'/src')

m = ['' for _ in range(100)]
util = ''
const = ''
# 引用带数字的py模组
for fileName in os.listdir('./src'):
    if fileName == 'util.py':
        util = importlib.import_module(fileName.replace('.py', '')).util
        continue
    if fileName == 'const.py':
        const = importlib.import_module(fileName.replace('.py', '')).const
        continue
    num = ''
    try:
        num = int(fileName[0:2])
        m[num] = importlib.import_module(fileName.replace('.py', ''))
        continue
    except ValueError:
        pass
    try:
        num = int(fileName[0])
        m[num] = importlib.import_module(fileName.replace('.py', ''))
        continue
    except ValueError:
        pass

def mainPrint():
    """ 菜单显示
    
    :returns: 选择的第几号脚本
    """
    printList = ['' for _ in range(100)]
    for fileName in os.listdir('./src'):
        try:
            num = int(fileName[0:2])
            printList[num] = fileName.replace('.py', '')
            continue
        except ValueError:
            pass
        try:
            num = int(fileName[0])
            printList[num] = fileName.replace('.py', '')
            continue
        except ValueError:
            pass
    for str in printList:
        if str != '':
            print(str)
    print('请输入数字来启动对应的脚本：')
    while True:
        str = input()
        for fileName in os.listdir('./src'):
            if str == fileName[0] or str == fileName[0:2]:
                return str
        print('请重新输入数字来启动对应的脚本：')

def adb(command):
    """ 执行adb指令 多带点输出
        
    :param command: adb的指令
    :returns: adb操作完成后的返回对象
    """
    util.logOut(__file__,'执行adb指令：{}'.format(command))
    ret = util.adb(command)
    util.logOut(__file__,format(ret))
    return ret

def initAdb():
    """ 初始化adb """
    util.logOut(__file__,'-------------adb初始化开始-------------')
    while True:
        adb('kill-server')
        ipPort = '127.0.0.1:7555'
        ret = adb('connect {}'.format(ipPort))
        if 'connected to '.format(ipPort) not in ret.stdout:
            # 需要尝试重新连接
            util.logOut(__file__,'-------------adb初始化失败，3秒后重新尝试初始化-------------')
            time.sleep(3)
            continue

        ret = adb('shell mkdir /storage/emulated/0/data')
        while ret.returncode != 0:
            time.sleep(1)
            ret = adb('shell mkdir /storage/emulated/0/data')
        ret = adb('shell mkdir /storage/emulated/0/data/screen')
        while ret.returncode != 0:
            time.sleep(1)
            ret = adb('shell mkdir /storage/emulated/0/data/screen')
        ret = adb('shell screencap /storage/emulated/0/data/screen/image.png')
        while ret.returncode != 0:
            time.sleep(1)
            ret = adb('shell screencap /storage/emulated/0/data/screen/image.png')

        # 判断图像能够传输出来
        ret = adb('pull /storage/emulated/0/data/screen/image.png .\\tmp')
        while ret.returncode != 0:
            time.sleep(1)
            ret = adb('pull /storage/emulated/0/data/screen/image.png .\\tmp')

        break
        
    util.logOut(__file__,'-------------adb初始化成功-------------')

if __name__ == '__main__':
    util.logOut(__file__,'====================')
    util.logOut(__file__,'碧蓝航线脚本启动')
    util.logOut(__file__,'====================')

    initAdb()

    # 判断截图尺寸
    width = 864
    height = 486
    img = cv2.imread("./tmp/image.png", 0)
    if len(img) != height or len(img[0]) != width:
        util.logOut(__file__,'请将模拟器的分辨率设置为{}:{}'.format(width, height))

    const.startAPP()

    while True:
        os.system("cls")
        index = int(mainPrint())
        while True:
            try:
                m[index].main()
                break
            except Exception as err:
                if str(err) != 'restart':
                    util.logOut(__file__,'====================')
                    util.logOut(__file__,'Exception err: {}'.format(err))
                    util.logOut(__file__,format(traceback.format_exc()))
                    util.logOut(__file__,'====================')
                const.restartProcess()
                continue

    # TODO 图像匹配 输出匹配度
    # TODO 打了一半去大世界 会出问题

        
